*Copyright Pierian Data 2017*
*For more information, visit us at www.pieriandata.com*

Stock Market Analysis Project

Please Note: You are free to treat this as a full exercise, or just view the solutions video as a code along project. This project is meant to be pretty challenging as it will introduce a few new concepts through some hints!

Welcome to your first capstone project! This project is meant to cap off the first half of the course, which mainly dealt with learning the libraries that we use in this course, the second half of the course will deal a lot more with quantitative trading techniques and platforms.

We'll be analyzing stock data related to a few car companies, from Jan 1 2012 to Jan 1 2017. Keep in mind that this project is mainly just to practice your skills with matplotlib, pandas, and numpy. Don't infer financial trading advice from the analysis we do here!

Part 0: Import

Import the various libraries you will need-you can always just come back up here or import as you go along :)


In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

Part 1: Getting the Data

Tesla Stock (Ticker: TSLA on the NASDAQ)

*Note! Not everyone will be working on a computer that will give them open access to download the stock information using pandas_datareader (firewalls, admin permissions, etc...). Because of this, the csv file for the Tesla is provided in a data folder inside this folder. It is called Tesla_Stock.csv. Feel free to just use this with read_csv!

Use pandas_datareader to obtain the historical stock information for Tesla from Jan 1, 2012 to Jan 1, 2017.


In [2]:
import pandas_datareader.data as web
import datetime
start = datetime.datetime(2012, 1, 1)
end = datetime.datetime(2017, 1, 1)
tesla_stock = web.DataReader('TSLA', 'google', start, end)
tesla_stock.head()


Out[2]:
Open High Low Close Volume
Date
2016-09-19 207.00 209.43 205.00 206.34 2299498
2016-09-20 206.85 207.75 203.91 204.64 2410488
2016-09-21 206.37 207.00 201.56 205.22 2633503
2016-09-22 206.40 207.28 203.00 206.43 2382902
2016-09-23 205.99 210.18 205.67 207.45 2905229

In [3]:
# CSV files is used since Google Finance does not provide full data.
tesla_stock = pd.read_csv('./Tesla_Stock.csv', 
                          index_col= 'Date')

In [4]:
tesla_stock.head()


Out[4]:
Open High Low Close Volume
Date
2012-01-03 28.94 29.50 27.65 28.08 928052
2012-01-04 28.21 28.67 27.50 27.71 630036
2012-01-05 27.76 27.93 26.85 27.12 1005432
2012-01-06 27.20 27.79 26.41 26.89 687081
2012-01-09 27.00 27.49 26.12 27.25 896951

Other Car Companies

Repeat the same steps to grab data for Ford and GM (General Motors),


In [5]:
ford_stock = pd.read_csv('./Ford_Stock.csv', index_col= 'Date')

In [6]:
ford_stock.head()


Out[6]:
Open High Low Close Volume
Date
2012-01-03 11.00 11.25 10.99 11.13 45709811
2012-01-04 11.15 11.53 11.07 11.30 79725188
2012-01-05 11.33 11.63 11.24 11.59 67877467
2012-01-06 11.74 11.80 11.52 11.71 59840605
2012-01-09 11.83 11.95 11.70 11.80 53981467

In [7]:
gm_stock = pd.read_csv('./GM_Stock.csv', index_col= 'Date')

In [8]:
gm_stock.head()


Out[8]:
Open High Low Close Volume
Date
2012-01-03 20.83 21.18 20.75 21.05 9321420
2012-01-04 21.05 21.37 20.75 21.15 7856752
2012-01-05 21.10 22.29 20.96 22.17 17884040
2012-01-06 22.26 23.03 22.24 22.92 18234608
2012-01-09 23.20 23.43 22.70 22.84 12091714

Part 2: Visualizing the Data

Time to visualize the data.

Follow along and recreate the plots below according to the instructions and explanations.


Recreate this linear plot of all the stocks' Open price ! Hint: For the legend, use label parameter and plt.legend()


In [9]:
# Code Here
fig = plt.figure(figsize = (12, 6))
plt.title('Open')

tesla_stock['Open'].plot(label = 'Tesla')
ford_stock['Open'].plot(label = 'Ford')
gm_stock['Open'].plot(label = 'GM')
plt.legend()


Out[9]:
<matplotlib.legend.Legend at 0x1a90d9e0160>

Plot the Volume of stock traded each day.


In [10]:
fig = plt.figure(figsize = (12, 6))
plt.title('Volume')

tesla_stock['Volume'].plot(label = 'Tesla')
ford_stock['Volume'].plot(label = 'Ford')
gm_stock['Volume'].plot(label = 'GM')
plt.legend()


Out[10]:
<matplotlib.legend.Legend at 0x1a90db7fc88>

Interesting, looks like Ford had a really big spike somewhere in late 2013. What was the date of this maximum trading volume for Ford?

Bonus: What happened that day?


In [11]:
ford_stock['Volume'].argmax()


Out[11]:
'2013-12-18'

In [12]:
# http://money.cnn.com/2013/12/18/news/companies/ford-profit/index.html

The Open Price Time Series Visualization makes Tesla look like its always been much more valuable as a company than GM and Ford. But to really understand this we would need to look at the total market cap of the company, not just the stock price. Unfortunately our current data doesn't have that information of total units of stock present. But what we can do as a simple calcualtion to try to represent total money traded would be to multply the Volume column by the Open price. Remember that this still isn't the actual Market Cap, its just a visual representation of the total amount of money being traded around using the time series. (e.g. 100 units of stock at \$10 each versus 100000 units of stock at $1 each)

Create a new column for each dataframe called "Total Traded" which is the Open Price multiplied by the Volume Traded.


In [13]:
# Code Here 
tesla_stock['Total Traded'] = tesla_stock['Open'] * tesla_stock['Volume']
ford_stock['Total Traded'] = ford_stock['Open'] * ford_stock['Volume']
gm_stock['Total Traded'] = gm_stock['Open'] * gm_stock['Volume']

Plot this "Total Traded" against the time index.


In [14]:
# Code here
fig = plt.figure(figsize = (12, 6))
plt.title('Total Traded')

tesla_stock['Total Traded'].plot(label = 'Tesla')
ford_stock['Total Traded'].plot(label = 'Ford')
gm_stock['Total Traded'].plot(label = 'GM')
plt.legend()


Out[14]:
<matplotlib.legend.Legend at 0x1a90dc16eb8>

In [ ]:

Interesting, looks like there was huge amount of money traded for Tesla somewhere in early 2014. What date was that and what happened?


In [15]:
tesla_stock['Total Traded'].argmax()


Out[15]:
'2014-02-25'

In [16]:
# http://money.cnn.com/2014/02/25/investing/tesla-record-high/

Let's practice plotting out some MA (Moving Averages). Plot out the MA50 and MA200 for GM.


In [17]:
# Code here

In [18]:
fig = plt.figure(figsize = (12, 6))
gm_stock.rolling(window = 50).mean()['Open'].plot(label = 'MA50')
gm_stock.rolling(window = 200).mean()['Open'].plot(label = 'MA200')
plt.legend()


Out[18]:
<matplotlib.legend.Legend at 0x1a90dbcf860>

Finally lets see if there is a relationship between these stocks, after all, they are all related to the car industry. We can see this easily through a scatter matrix plot. Import scatter_matrix from pandas.plotting and use it to create a scatter matrix plot of all the stocks'opening price. You may need to rearrange the columns into a new single dataframe. Hints and info can be found here: https://pandas.pydata.org/pandas-docs/stable/visualization.html#scatter-matrix-plot


In [19]:
from pandas.plotting import scatter_matrix

In [20]:
df = pd.concat([tesla_stock['Open'], ford_stock['Open'], gm_stock['Open']], axis = 1)
df.columns = ['Tesla', 'Ford', 'GM']
df.head()


Out[20]:
Tesla Ford GM
Date
2012-01-03 28.94 11.00 20.83
2012-01-04 28.21 11.15 21.05
2012-01-05 27.76 11.33 21.10
2012-01-06 27.20 11.74 22.26
2012-01-09 27.00 11.83 23.20

In [21]:
scatter_matrix(df, figsize = (10, 10), hist_kwds = {'bins' : 100})


Out[21]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000001A90DF00A90>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A90DFFEEB8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A90DF7E630>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x000001A90F2D4C88>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A90F334198>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A90F3341D0>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x000001A90F54FE48>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A90F5C49B0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A90F632588>]], dtype=object)

Bonus Visualization Task! (Note: This is hard!)

Let's now create a candlestick chart! Watch the video if you get stuck on trying to recreate this visualization, there are quite a few steps involved!Refer to the video to understand how to interpret and read this chart. Hints: https://matplotlib.org/examples/pylab_examples/finance_demo.html

Create a CandleStick chart for Ford in January 2012 (too many dates won't look good for a candlestick chart)


In [22]:
start = '2012-01'
end = '2012-02'
ford_candle = ford_stock.loc[start:end]

In [23]:
# To be continued

Part 3: Basic Financial Analysis

Now it is time to focus on a few key financial calculations. This will serve as your transition to the second half of the course. All you need to do is follow along with the instructions, this will mainly be an exercise in converting a mathematical equation or concept into code using python and pandas, something we will do often when working with quantiative data! If you feel very lost in this section, don't worry! Just go to the solutions lecture and treat it as a code-along lecture, use whatever style of learning works best for you!

Let's begin!


Daily Percentage Change

First we will begin by calculating the daily percentage change. Daily percentage change is defined by the following formula:

$ r_t = \frac{p_t}{p_{t-1}} -1$

This defines r_t (return at time t) as equal to the price at time t divided by the price at time t-1 (the previous day) minus 1. Basically this just informs you of your percent gain (or loss) if you bought the stock on day and then sold it the next day. While this isn't necessarily helpful for attempting to predict future values of the stock, its very helpful in analyzing the volatility of the stock. If daily returns have a wide distribution, the stock is more volatile from one day to the next. Let's calculate the percent returns and then plot them with a histogram, and decide which stock is the most stable!

Create a new column for each dataframe called returns. This column will be calculated from the Close price column. There are two ways to do this, either a simple calculation using the .shift() method that follows the formula above, or you can also use pandas' built in pct_change method.


In [24]:
tesla_stock['returns'] = (tesla_stock['Close'] / tesla_stock['Close'].shift(1)) - 1

In [25]:
tesla_stock.head()


Out[25]:
Open High Low Close Volume Total Traded returns
Date
2012-01-03 28.94 29.50 27.65 28.08 928052 26857824.88 NaN
2012-01-04 28.21 28.67 27.50 27.71 630036 17773315.56 -0.013177
2012-01-05 27.76 27.93 26.85 27.12 1005432 27910792.32 -0.021292
2012-01-06 27.20 27.79 26.41 26.89 687081 18688603.20 -0.008481
2012-01-09 27.00 27.49 26.12 27.25 896951 24217677.00 0.013388

In [26]:
ford_stock['returns'] = (ford_stock['Close'] / ford_stock['Close'].shift(1)) - 1
gm_stock['returns'] = (gm_stock['Close'] / gm_stock['Close'].shift(1)) - 1

Now plot a histogram of each companies returns. Either do them separately, or stack them on top of each other. Which stock is the most "volatile"? (as judged by the variance in the daily returns we will discuss volatility in a lot more detail in future lectures.)


In [27]:
# Separately
fig = plt.figure(0)
tesla_stock['returns'].plot(kind = 'hist', bins = 50)
plt.title('Tesla')

plt.show()

fig = plt.figure(1)
ford_stock['returns'].plot(kind = 'hist', bins = 50)
plt.title('Ford')
plt.show()

fig = plt.figure(2)
gm_stock['returns'].plot(kind = 'hist', bins = 50)
plt.title('GM')
plt.show()



In [28]:
# On one graph.
fig = plt.figure(figsize = (12, 10))
tesla_stock['returns'].plot(kind = 'hist', 
                            bins = 50, 
                            label = 'Tesla', 
                            alpha = 0.5)
ford_stock['returns'].plot(kind = 'hist', 
                            bins = 50, 
                            label = 'Ford',
                            alpha = 0.8)
gm_stock['returns'].plot(kind = 'hist', 
                            bins = 50, 
                            label = 'GM', 
                            alpha = 0.4)
plt.legend()


Out[28]:
<matplotlib.legend.Legend at 0x1a91032bac8>

Try also plotting a KDE instead of histograms for another view point. Which stock has the widest plot?


In [29]:
fig = plt.figure(figsize = (12, 10))
tesla_stock['returns'].plot(kind = 'kde', 
                            label = 'Tesla', 
                            alpha = 0.5)
ford_stock['returns'].plot(kind = 'kde', 
                           label = 'Ford',
                           alpha = 0.8)
gm_stock['returns'].plot(kind = 'kde',
                         label = 'GM', 
                         alpha = 0.4)
plt.legend()


Out[29]:
<matplotlib.legend.Legend at 0x1a91042ce10>

Try also creating some box plots comparing the returns.


In [30]:
box_df = pd.concat([tesla_stock['returns'], ford_stock['returns'], gm_stock['returns']], axis = 1)
box_df.columns = ['Tesla', 'Ford', 'GM']
box_df.plot(kind = 'box', figsize = (12, 10))
plt.legend()


C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py:545: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots.
  warnings.warn("No labelled objects found. "

Comparing Daily Returns between Stocks

Create a scatter matrix plot to see the correlation between each of the stocks daily returns. This helps answer the questions of how related the car companies are. Is Tesla begin treated more as a technology company rather than a car company by the market?


In [31]:
from pandas.plotting import scatter_matrix

scatter_matrix(box_df, figsize = (10, 10), hist_kwds={'bins':50})


Out[31]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000001A910D77668>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A910F3DF98>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A910EDB240>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x000001A9111D6978>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A911235B00>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A911235B38>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x000001A91131A128>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A911355518>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001A9115C0A58>]], dtype=object)

It looks like Ford and GM do have some sort of possible relationship, let's plot just these two against eachother in scatter plot to view this more closely!


In [32]:
fig = plt.figure(figsize = (12, 8))
plt.scatter(ford_stock['returns'], gm_stock['returns'])


Out[32]:
<matplotlib.collections.PathCollection at 0x1a911788240>

Cumulative Daily Returns

Great! Now we can see which stock was the most wide ranging in daily returns (you should have realized it was Tesla, our original stock price plot should have also made that obvious).

With daily cumulative returns, the question we are trying to answer is the following, if I invested $1 in the company at the beginning of the time series, how much would is be worth today? This is different than just the stock price at the current day, because it will take into account the daily returns. Keep in mind, our simple calculation here won't take into account stocks that give back a dividend. Let's look at some simple examples:

Lets us say there is a stock 'ABC' that is being actively traded on an exchange. ABC has the following prices corresponding to the dates given

Date                        Price
01/01/2018                   10
01/02/2018                   15
01/03/2018                   20
01/04/2018                   25

Daily Return : Daily return is the profit/loss made by the stock compared to the previous day. (This is what ew just calculated above). A value above one indicates profit, similarly a value below one indicates loss. It is also expressed in percentage to convey the information better. (When expressed as percentage, if the value is above 0, the stock had give you profit else loss). So for the above example the daily returns would be

Date                         Daily Return                  %Daily Return
01/01/2018                 10/10 =  1                          -   
01/02/2018                 15/10 =  3/2                       50%
01/03/2018                 20/15 =  4/3                       33%
01/04/2018                 25/20 =  5/4                       20%

Cumulative Return: While daily returns are useful, it doesn't give the investor a immediate insight into the gains he had made till date, especially if the stock is very volatile. Cumulative return is computed relative to the day investment is made. If cumulative return is above one, you are making profits else you are in loss. So for the above example cumulative gains are as follows

Date                       Cumulative Return         %Cumulative Return
01/01/2018                  10/10 =  1                         100 %   
01/02/2018                  15/10 =  3/2                       150 %
01/03/2018                  20/10 =  2                         200 %
01/04/2018                  25/10 =  5/2                       250 %

The formula for a cumulative daily return is:

$ i_i = (1+r_t) * i_{t-1} $

Here we can see we are just multiplying our previous investment at i at t-1 by 1+our percent returns. Pandas makes this very simple to calculate with its cumprod() method. Using something in the following manner:

df[daily_cumulative_return] = ( 1 + df[pct_daily_return] ).cumprod()

Create a cumulative daily return column for each car company's dataframe.


In [33]:
tesla_stock['Cumulative Return'] = (1 + tesla_stock['returns']).cumprod()
tesla_stock.head()


Out[33]:
Open High Low Close Volume Total Traded returns Cumulative Return
Date
2012-01-03 28.94 29.50 27.65 28.08 928052 26857824.88 NaN NaN
2012-01-04 28.21 28.67 27.50 27.71 630036 17773315.56 -0.013177 0.986823
2012-01-05 27.76 27.93 26.85 27.12 1005432 27910792.32 -0.021292 0.965812
2012-01-06 27.20 27.79 26.41 26.89 687081 18688603.20 -0.008481 0.957621
2012-01-09 27.00 27.49 26.12 27.25 896951 24217677.00 0.013388 0.970442

In [34]:
ford_stock['Cumulative Return'] = (1 + ford_stock['returns']).cumprod()
gm_stock['Cumulative Return'] = (1 + gm_stock['returns']).cumprod()

Now plot the Cumulative Return columns against the time series index. Which stock showed the highest return for a $1 invested? Which showed the lowest?


In [35]:
fig = plt.figure(figsize = (12, 6))
tesla_stock['Cumulative Return'].plot(label = 'Tesla')
ford_stock['Cumulative Return'].plot(label = 'Ford')
gm_stock['Cumulative Return'].plot(label = 'GM')
plt.legend()


Out[35]:
<matplotlib.legend.Legend at 0x1a9119b0908>

Great Job!

That is it for this very basic analysis, this concludes this half of the course, which focuses much more on learning the tools of the trade. The second half of the course is where we really dive into functionality designed for time series, quantitative analysis, algorithmic trading, and much more!